package com.wolfalpha.utron.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.wolfalpha.utron.R;
import com.wolfalpha.utron.app.AppContext;
import com.wolfalpha.utron.service.FileService;
import com.wolfalpha.utron.service.ProjectService;
import com.wolfalpha.utron.service.impl.FileServiceImpl;
import com.wolfalpha.utron.service.impl.ProjectServiceImpl;
import com.wolfalpha.utron.ui.UIHelper;
import com.wolfalpha.utron.utils.FileUtils;
import com.wolfalpha.utron.utils.StringUtils;
import com.wolfalpha.utron.utils.ThreadPoolUtils;
import com.wolfalpha.utron.view.CallsAlertDialog;
import com.wolfalpha.utron.view.CircleImageView;
import com.wolfalpha.utron.view.CityAlertDialog;
import com.wolfalpha.utron.view.DirsAlertDialog;
import com.wolfalpha.utron.view.EditAlertDialog;
import com.wolfalpha.utron.view.ListAlertDialog;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

/**
 * 项目发布编辑界面
 * <p/>
 * Created by luodon on 15/8/21.
 */
public class ProjectPublishActivity extends Activity implements View.OnClickListener {

    private EditText etProgress;//项目进展
    private EditText etTeamer;  //团队
    private EditText etName;    //项目名编辑
    private EditText etDetail;  //项目详细信息
    private EditText etIntro;   //项目简介
    private EditText etCall;    //召唤类型

    private TextView tvDir;     //选择的方向
    private TextView tvLoc;     //选择的地点

    private CircleImageView cvLogo;//项目LOGO

    private LinearLayout llLocation;   //地址
    private LinearLayout llDir;        //方向

    private CheckBox cbYes;             //是
    private CheckBox cbNo;              //否

    private File f = null;
    private FileService fileService = null;

    private ProjectService projectService;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_project_publish);
        fileService = new FileServiceImpl();
        projectService = new ProjectServiceImpl();

        initView();
        initListeners();
    }

    private final int SUCCESS = 1;
    private final int FAIL = 2;
    private final int SHOW = 3;
    private final int DIR_FINISH = 4;


    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SUCCESS:
                    UIHelper.ToastMessage(ProjectPublishActivity.this, "发布成功");
                    finish();
                    break;
                case FAIL:
                    UIHelper.ToastMessage(ProjectPublishActivity.this, "发布失败");
                    break;
                case SHOW:
                    break;
                case DIR_FINISH:
                    if (dir_choose != -1) {
                        tvDir.setText(msg.obj.toString());
                    }
                    break;
            }
        }
    };


    /**
     * 左侧操作
     *
     * @param view
     */
    public void leftOperation(View view) {

        finish();
    }


    /**
     * 初始化界面
     */
    private void initView() {
        etProgress = (EditText) findViewById(R.id.et_project_publish_progress);
        llDir = (LinearLayout) findViewById(R.id.ll_project_publish_dir);
        llLocation = (LinearLayout) findViewById(R.id.ll_project_publish_location);
        cvLogo = (CircleImageView) findViewById(R.id.cv_project_publish_logo);
        etName = (EditText) findViewById(R.id.et_project_publish_name);
        etDetail = (EditText) findViewById(R.id.et_project_publish_detail);
        etCall = (EditText) findViewById(R.id.et_project_publish_call);
        etIntro = (EditText) findViewById(R.id.et_project_publish_intro);
        etTeamer = (EditText) findViewById(R.id.et_project_publish_teamer);

        tvDir = (TextView) findViewById(R.id.tv_project_publish_dir);
        tvLoc = (TextView) findViewById(R.id.tv_project_publish_location);

        cbYes = (CheckBox) findViewById(R.id.cb_project_publish_yes);
        cbNo = (CheckBox) findViewById(R.id.cb_project_publish_no);
    }

    /**
     * 初始化监听器
     */
    private void initListeners() {
        etDetail.setOnClickListener(this);
        etCall.setOnClickListener(this);
        etProgress.setOnClickListener(this);
        etTeamer.setOnClickListener(this);
        etIntro.setOnClickListener(this);
        cvLogo.setOnClickListener(this);
        llLocation.setOnClickListener(this);
        llDir.setOnClickListener(this);

        cbYes.setOnClickListener(this);
        cbNo.setOnClickListener(this);
    }

    @Override
    protected void onResume() {
        super.onResume();

        if ((detail = (String) AppContext.getInstance().getMemCache("project_publish_detail")) != null) {
            etDetail.setText(detail);
        }

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.cv_project_publish_logo:
                //选择上传LOGO
                showPickPhoto();
                break;
            case R.id.et_project_publish_progress:
                //选择项目阶段
                showProgress();
                break;
            case R.id.et_project_publish_call:
                //点击选择召唤类型
                showCalls();
                break;
            case R.id.et_project_publish_teamer:
                //点击选择团队人数
                showTeamers();
                break;
            case R.id.et_project_publish_detail:
                //输入项目详细介绍
                UIHelper.showActivity(ProjectPublishActivity.this, ProjectPublishDetailActivity.class);
                break;
            case R.id.et_project_publish_intro:
                //输入项目一句话介绍
                showIntroEdit();
                break;
            case R.id.ll_project_publish_dir:
                showDirsChoose();
                break;
            case R.id.ll_project_publish_location:
                //选择项目地区
                showLocChoose();
                break;
            case R.id.cb_project_publish_yes:
                //选择公开
                cbYes.setChecked(true);
                cbNo.setChecked(false);
                owner = 0;
                break;
            case R.id.cb_project_publish_no:
                //选择不公开
                cbYes.setChecked(false);
                cbNo.setChecked(true);
                owner = 1;
                break;
        }
    }

    /**
     * 完成并保存
     */
    public void rightOperation(View view) {
        p_name = etName.getText().toString().trim();
        if (dir_choose != -1
                && !TextUtils.isEmpty(loc_choose)
                && !TextUtils.isEmpty(p_name)
                && !TextUtils.isEmpty(progress)
                && !TextUtils.isEmpty(teamer)
                && !TextUtils.isEmpty(intro)
                && !TextUtils.isEmpty(detail)
                && !TextUtils.isEmpty(logo)
                && !TextUtils.isEmpty(calls)
                ) {

            ThreadPoolUtils.execute(new Runnable() {
                @Override
                public void run() {
                    System.out.println("a");
                    boolean up = projectService.publish(p_name, dir_choose, loc_choose, progress, teamer, intro, detail, logo, calls, owner);
                    if (up) {
                        handler.sendEmptyMessage(SUCCESS);
                    } else {
                        handler.sendEmptyMessage(FAIL);
                    }
                }
            });
        } else {
            UIHelper.ToastMessage(ProjectPublishActivity.this, "信息不完整，请完善信息");
        }

//        if (userInfo != null)
//
//            });
    }

    //存储信息
    private int dir_choose = -1;
    private String loc_choose = "";
    private String p_name = "";
    private String progress = "";
    private String teamer = "";
    private String intro = "";
    private String detail = "";
    private String logo = "";
    private String calls = "";
    private int owner = 0;

    private static final int IMAGE_REQUEST_CODE = 0;
    private static final int CAMERA_REQUEST_CODE = 1;
    private static final int RESIZE_REQUEST_CODE = 2;

    private static final String IMAGE_FILE_NAME = "utron/imageCache/project_logo.jpg";//头像拍照路径

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != RESULT_OK) {
            return;
        } else {
            switch (requestCode) {
                case IMAGE_REQUEST_CODE:
                    resizeImage(data.getData());
                    break;
                case CAMERA_REQUEST_CODE:
                    if (FileUtils.checkSDExists()) {
                        resizeImage(getImageUri());
                    } else {
                        UIHelper.ToastMessage(ProjectPublishActivity.this, "没有存储卡");
                    }
                    break;

                case RESIZE_REQUEST_CODE:
                    if (data != null) {
                        showResizeImage(data);
                    }
                    break;
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 对图片进行裁剪
     *
     * @param uri
     */

    public void resizeImage(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 300);
        intent.putExtra("outputY", 300);
        intent.putExtra("scale", true);
        intent.putExtra("output", getImageUri());  // 传入目标文件
        intent.putExtra("return-data", true);
        intent.putExtra("outputFormat", "JPEG"); //输入文件格式
        startActivityForResult(intent, RESIZE_REQUEST_CODE);
    }

    /**
     * 选召唤类型
     */
    private void showPickPhoto() {
        final ListAlertDialog ad = new ListAlertDialog(ProjectPublishActivity.this);
        ad.setTitle("选择项目LOGO");
        final String[] arr = new String[]{"本地上传", "拍照"};
        ad.setArray(arr);
        ad.setOnFinishedListener(new ListAlertDialog.OnFinishedListener() {
            @Override
            public void finish(int input) {
                if (input == 0) {
                    //本地上传
                    Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT);
                    galleryIntent.addCategory(Intent.CATEGORY_OPENABLE);
                    galleryIntent.setType("image/*");
                    startActivityForResult(galleryIntent, IMAGE_REQUEST_CODE);
                }
                if (input == 1) {
                    //拍照上传
                    if (FileUtils.checkSDExists()) {
                        Intent cameraIntent = new Intent(
                                "android.media.action.IMAGE_CAPTURE");
                        cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, getImageUri());
                        cameraIntent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 0);
                        startActivityForResult(cameraIntent, CAMERA_REQUEST_CODE);
                    } else {
                        UIHelper.ToastMessage(ProjectPublishActivity.this, "请先插入SD卡");
                    }
                }
            }
        });
    }


    /**
     * 显示头像图片
     *
     * @param data
     */
    private void showResizeImage(Intent data) {
        Handler handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if (f == null) return;
                ThreadPoolUtils.execute(new Runnable() {
                    @Override
                    public void run() {
                        String res = fileService.upload(f);
                        if (res != null) {
                            logo = res;
                        } else {
                            UIHelper.ToastMessage(ProjectPublishActivity.this, "上传LOGO失败");
                        }
                    }
                });
            }
        };
        Bundle extras = data.getExtras();
        if (extras != null) {
            Bitmap photo = extras.getParcelable("data");

            try {
                f = getImage();
                FileOutputStream fOut = null;
                try {
                    fOut = new FileOutputStream(f);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
                photo.compress(Bitmap.CompressFormat.PNG, 100, fOut);
                fOut.flush();
                fOut.close();
                if (f != null) handler.sendEmptyMessage(0);
            } catch (IOException e) {
                e.printStackTrace();
            }

            Drawable drawable = new BitmapDrawable(photo);
            cvLogo.setImageDrawable(drawable);
        }
    }


    /**
     * 获取图片内容
     *
     * @return
     */
    private File getImage() {
        return new File(Environment.getExternalStorageDirectory(),
                IMAGE_FILE_NAME);
    }

    /**
     * 获取图像地址
     *
     * @return
     */
    private Uri getImageUri() {
        return Uri.fromFile(new File(Environment.getExternalStorageDirectory(),
                IMAGE_FILE_NAME));
    }


    /**
     * 选召唤类型
     */
    private void showProgress() {
        final ListAlertDialog ad = new ListAlertDialog(ProjectPublishActivity.this);
        ad.setTitle("选择项目目前的阶段");
        final String[] arr = this.getResources().getStringArray(R.array.project_progress);
        ad.setArray(arr);
        ad.setOnFinishedListener(new ListAlertDialog.OnFinishedListener() {
            @Override
            public void finish(int input) {
                etProgress.setText(arr[input]);
                progress = arr[input];
            }
        });
    }

    /**
     * 选召唤类型
     */
    private void showTeamers() {
        final ListAlertDialog ad = new ListAlertDialog(ProjectPublishActivity.this);
        ad.setTitle("选择团队建设总人数");
        final String[] arr = this.getResources().getStringArray(R.array.project_teamer);
        ad.setArray(arr);
        ad.setOnFinishedListener(new ListAlertDialog.OnFinishedListener() {
            @Override
            public void finish(int input) {
                etTeamer.setText(arr[input]);
                teamer = arr[input];
            }
        });
    }

    /**
     * 选召唤类型
     */
    private void showCalls() {
        final CallsAlertDialog ad = new CallsAlertDialog(ProjectPublishActivity.this);
        ad.setOnFinishedListener(new CallsAlertDialog.OnFinishedListener() {
            @Override
            public void finish(String input) {
                etCall.setText(input);
                calls = input;
            }
        });
    }

    /**
     * 选择地区
     */
    private void showIntroEdit() {
        final EditAlertDialog ad = new EditAlertDialog(ProjectPublishActivity.this);
        ad.setOnFinishedListener(new EditAlertDialog.OnFinishedListener() {
            @Override
            public void finish(String input) {
                etIntro.setText(input);
                intro = input;
            }
        });
    }

    /**
     * 选择方向
     */
    private void showDirsChoose() {
        final DirsAlertDialog ad = new DirsAlertDialog(ProjectPublishActivity.this, true);
        ad.setTitle("选择方向");
        final List<String> data = StringUtils.getDirsValues(ProjectPublishActivity.this);
        ad.setData(data);
        ad.setPositiveButton("确认", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dir_choose = (ad.getResult() == null || ad.getResult().size() == 0) ? -1 : ad.getResult().get(0);
                if (dir_choose != -1) {
                    tvDir.setText(data.get(dir_choose));

                    dir_choose += 1001;
                }
                ad.dismiss();
            }
        });
    }

    /**
     * 选择地区
     */
    private void showLocChoose() {
        final CityAlertDialog ad = new CityAlertDialog(ProjectPublishActivity.this);
        ad.setTitle("选择项目发起地");

        ad.setPositiveButton("确认", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ad.getSelected() == null) {
                    UIHelper.ToastMessage(ProjectPublishActivity.this, "您未选择任何选项");
                } else {
                    System.out.println(ad.getSelected());
                    tvLoc.setText(ad.getSelected());
                    loc_choose = ad.getSelected();
                }
                ad.dismiss();
            }
        });

        ad.setNegativeButton("取消", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ad.dismiss();
            }
        });
    }
}
